layui.use(['form', 'admin', 'ax', 'table', 'laytpl', 'element'], function () {
    var $ax = layui.ax;
    var admin = layui.admin;
    var table = layui.table;
    var form = layui.form;
    var laytpl = layui.laytpl;
    var element = layui.element;

    var Current = {
        tableId: "table"
    };

    // 搜索
    form.on('submit(btnSubmit)', function (data) {
        table.reload(Current.tableId, {where: data.field});
        return false;
    });

    //获取所有可筛选服务
    var ajax = new $ax(system.contextPath + "/api/registry.service.lists");
    ajax.setType("get");
    var result = ajax.start();
    if (result.status) {
        var data = result.data;
        var list = [];
        for (var i = 0; i < data.length; i++) {
            var param = {};
            param['name'] = data[i];
            list.push(param);
        }
        var data0 = {
            list: list,
        };
        var part0Temp = document.getElementById('part0-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            document.getElementById('part0').innerHTML = html;
            form.render();
        });
    }

    var tipsLayer;
    window.showTips = function (t) {
        const title = '限流策略';
        const windowRemark = '窗口策略：每秒处理固定数量的请求，超出请求数量返回错误信息。'
        const tokenRemark = '令牌桶策略：每秒放置固定数量的令牌数，每个请求进来后先去拿令牌，拿到了令牌才能继续，拿不到则等候令牌重新生成了再拿。'
        const content = title + '<br>' + windowRemark + '<br><br>' + tokenRemark
        //小tips
        tipsLayer=layer.tips(content, t, {
            tips: [1, '#8f8f8f'],
            time: 40000000
        })
    }

    window.closeTips = function () {
        layer.close(tipsLayer);
    }
    Current.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'serviceId', sort: false, title: '服务名称'},
            {
                field: 'routeId', sort: false, title: '限流维度', templet: function (d) {
                    var result = [];
                    var title = [];
                    var routeId = d.routeId;
                    var appKey = d.appKey;
                    var limitIp = d.limitIp;
                    if (routeId != null && routeId != '') {
                        result.push(routeId);
                        title.push("路由ID");
                    }
                    if (appKey != null && appKey != '') {
                        result.push(appKey);
                        title.push("AppId");
                    }
                    if (limitIp != null && limitIp != '') {
                        result.push(limitIp);
                        title.push("Ip");
                    }
                    return '(' + title.join('+') + ')\n\n' + result.join('+');

                }
            },
            {
                field: 'limitType',
                sort: false,
                title: '限流策略 <i class="layui-icon layui-icon-help" style="color: orange" onmouseover="showTips(this)" onmouseout="closeTips()"></i>',
                templet: function (d) {
                    //1：窗口策略，2：令牌桶策略
                    return d.limitType === 1 ? '窗口策略' : '令牌桶策略';
                }
            },
            {
                field: 'durationSeconds', sort: false, title: '限流信息', templet: function (d) {
                    return d.limitType === 1 ? '每 ' + d.durationSeconds + ' 秒可处理 ' + d.execCountPerSecond + ' 个请求' : '令牌桶容量：' + d.tokenBucketCount;
                }
            },
            {
                field: 'limitStatus', sort: false, title: '状态', templet: function (d) {
                    return d.limitStatus === 1 ? '<span style="color: rgb(103, 194, 58);">已开启</span>' : '已关闭';
                }
            },
            {field: 'orderIndex', sort: false, title: '排序'},
            {field: 'remark', sort: false, title: '备注'},
            {field: 'gmtCreate', sort: false, title: '创建时间'},
            {field: 'gmtModified', sort: false, title: '修改时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    var ins = table.render({
        elem: '#' + Current.tableId,
        url: system.contextPath + '/api/config.limit.lists',
        page: true,
        request: {
            pageName: 'pageIndex' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        height: "full-158",
        cols: Current.initColumn(),
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        }
        , response: {
            statusCode: 200
        }
        , size: 'lg',
        done: function (res, curr, count) {
            count || this.elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'visible');
            $('.layui-table-body').find('div.layui-table-cell').find('select').each(function () {
                var $this = $(this);
                var val = $this.data('value');
                var text;
                $(this).children().each(function () {
                    if (val == this.value) {
                        text = this.text;
                        return;
                    }
                })
                //更新layui 选择器输入框的值
                $this.next().find('.layui-select-title').find('input').val(text);
                //更新layui 选择器的值 以及设置其样式
                $this.val(val).parents('div.layui-table-cell').css('overflow', 'visible');
            })
            form.render(null, 'table');
        }
    });

    Current.onEdit = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '编辑',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/limit/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId)
            }
        });
    };

    Current.onAdd = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/limit/add',
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId)
            }
        });
    };

    Current.onDelete = function (data) {
        var operation = function () {
            var ajax = new $ax(system.contextPath + "/api/ip.blacklist.del", function (res) {
                if (res.status) {
                    system.success("删除成功!");
                    //重新加载表格
                    table.reload(Current.tableId)
                } else {
                    system.error("删除失败!" + res.msg + "!");
                }
            }, function (res) {
                system.error("删除失败!" + res.msg + "!");
            });
            ajax.set({id: data.id});
            ajax.start();
        };
        system.confirm("是否删除?", operation);
    };

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Current.onAdd();
        return false;
    });

    // 工具条点击事件
    table.on('tool(' + Current.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Current.onEdit(data);
        } else if (layEvent === 'delete') {
            Current.onDelete(data);
        }
    });


});
